<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form" v-if="headerShow">
        <a-form
          size="small"
          :model="pageData"
          layout="inline"
          :label-col-props="{ span: 8 }"
          :wrapper-col-props="{ span: 16 }"
        >
          <CorporateSectorCascader
            ref="cascaderRef"
            :configCascader="configCascader"
            @changeCascader="changeCascader"
          />
          <a-form-item
            style="width: 280px"
            label="织布单号"
            label-col-flex="100px"
            v-if="permissionStore.hasPermisson('jyyccx.cx')"
          >
            <a-input
              :style="{ width: '250px' }"
              class="bacClass"
              v-model="pageData.planOrderCode"
              @press-enter="huiche"
              allow-clear
            ></a-input>
          </a-form-item>

          <a-form-item
            style="width: 280px"
            label="坯布编号"
            label-col-flex="100px"
            v-if="permissionStore.hasPermisson('jyyccx.cx')"
          >
            <a-input
              class="bacClass"
              placeholder=""
              v-model="pageData.greigeCode"
              @press-enter="huiche"
              allow-clear
            />
          </a-form-item>

          <a-form-item
            style="width: 280px"
            label="坯布名称"
            label-col-flex="100px"
            v-if="permissionStore.hasPermisson('jyyccx.cx')"
          >
            <a-input
              class="bacClass"
              placeholder=""
              v-model="pageData.greigeName"
              @press-enter="huiche"
              allow-clear
            />
          </a-form-item>

          <a-form-item
            style="width: 280px"
            label="处理方式"
            label-col-flex="100px"
            v-if="permissionStore.hasPermisson('jyyccx.cx')"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              :style="{ width: '200px' }"
              v-model="pageData.resultCode"
              allow-clear
            >
              <a-option label="本厂修补" value="0"></a-option>
              <a-option label="委外修补" value="1"></a-option>
              <a-option label="入次布仓" value="2"></a-option>
            </a-select>
          </a-form-item>

          <a-form-item
            style="width: 280px"
            label="处理人"
            label-col-flex="100px"
            v-if="permissionStore.hasPermisson('jyyccx.cx')"
          >
            <a-input
              class="bacClass"
              placeholder=""
              v-model="pageData.updateName"
              @press-enter="huiche"
              allow-clear
            />
          </a-form-item>

          <a-form-item
            style="width: 380px"
            label="处理日期"
            label-col-flex="100px"
            v-if="permissionStore.hasPermisson('jyyccx.cx')"
          >
            <a-range-picker
              popup-container="html"
              class="bacClass"
              v-model="pageData.disposeDate"
              allow-clear
              @press-enter="huiche"
            />
          </a-form-item>
        </a-form>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar
          :items="pageData.btnList"
          @select="selectHandler"
          @dyBoufei="handleClick"
          @createPatchOrder="createPatchOrder"
          @exportAll="exportAll"
        >
        </Toolbar>
      </div>
      <a-drawer
        style="z-index: 999"
        ok-text="保存"
        cancel-text="取消"
        :drawer-style="{ border: '1px solid #ccc' }"
        popup-container=".arco-tabs-content"
        height="89vh"
        placement="bottom"
        :visible="drawer"
        unmountOnClose
        @ok="save"
        @cancel="drawer = false"
      >
        <template #title> 创建修补单 </template>
        <el-form
          v-loading="loadingElplus"
          ref="ruleFormRef"
          :model="ruleForm"
          label-width="120px"
          class="demo-ruleForm"
          status-icon
          size="default"
        >
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="公司" prop="outSouringCompany">
                <div style="display: flex">
                  <el-input style="width: 200px" v-model="ruleForm.outSouringCompany" disabled />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="修补人员" prop="repairUser">
                <div style="display: flex">
                  <el-select
                    v-model="ruleForm.repairUser"
                    multiple
                    clearable
                    popper-class="repairman-options"
                    suffix-icon="none"
                    :suffix-transition="false"
                    style="width: 200px"
                    @remove-tag="handleRemoveTag"
                  >
                    <!-- <el-option
                      v-for="item in repairmanList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    /> -->
                  </el-select>
                  <el-button type="primary" style="margin-left: 2px" @click="clickRepairman"
                    >选择</el-button
                  >
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="开始时间" prop="startDate ">
                <el-date-picker
                  v-model="ruleForm.startDate"
                  type="datetime"
                  placeholder="请选择开始时间"
                  format="YYYY/MM/DD HH:mm"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="结束时间" prop="endDate">
                <el-date-picker
                  v-model="ruleForm.endDate"
                  type="datetime"
                  placeholder="请选择结束时间"
                  format="YYYY/MM/DD HH:mm"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="金额" prop="amount">
                <el-input-number :precision="2" v-model="ruleForm.amount" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="ruleForm.remark" :rows="1" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-table
            :data="tableData"
            border
            :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ 'text-align': 'center' }"
            style="width: 100%"
          >
            <el-table-column label="检验单号" prop="checkoutOdd" />
            <el-table-column label="计划单号" prop="planOrderCode" width="160" />
            <el-table-column label="坯布编号" prop="greigeCode" width="160" />
            <el-table-column label="坯布名称" prop="greigeName" width="300" />
            <el-table-column label="机台号" prop="machineOdd" width="80" />
            <el-table-column label="匹号" prop="loneOdd" width="80" />
            <el-table-column label="问题点" prop="defectNames" />
            <el-table-column label="处理方式" prop="resultCode" />
            <el-table-column label="检验日期" prop="checkoutDate" width="180" />
          </el-table>
        </el-form>
      </a-drawer>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <!--表格插件-->
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          :suppressCopyRowsToClipboard="true"
          :suppressDragLeaveHidesColumns="true"
          :localeText="localeText1"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: 100%"
          @columnVisible="onColumnVisible"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :columnDefs="tc"
          @columnResized="onColumnResized"
          @columnMoved="onColumnMoved"
        >
        </AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys
      :total="total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
      :page-size="size"
      :current="page"
      :page-size-options="pagingList1"
    />
    <a-modal
      v-model:visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      ok-text="打印"
      :width="1000"
      draggable
    >
      <template #title> 打印修补单 </template>
      <div id="inspect">
        <h1 style="text-align: center; width: 100%">修补单</h1>
        <table id="Table">
          <thead>
            <tr>
              <td class="tdStyle">检验单号</td>
              <td class="tdStyle">计划单号</td>
              <td class="tdStyle">坯布编号</td>
              <td class="tdStyle">坯布名称</td>
              <td class="tdStyle">机号</td>
              <td class="tdStyle">匹号</td>
              <td class="tdStyle">处理方式</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in pageData.printData" :key="index">
              <td class="tdStyle">{{ item['checkoutOdd'] }}</td>
              <td class="tdStyle">{{ item['planOrderCode'] }}</td>
              <td class="tdStyle">{{ item['greigeCode'] }}</td>
              <td class="tdStyle">{{ item['greigeName'] }}</td>
              <td class="tdStyle">{{ item['machineOdd'] }}</td>
              <td class="tdStyle">{{ item['loneOdd'] }}</td>
              <td class="tdStyle">{{ item['resultCode'] == 1 ? '委外修补' : '本厂修补' }}</td>
            </tr>
            <tr>
              <td>总匹数</td>
              <td colspan="6">{{ pageData.printData.length }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </a-modal>
    <a-modal
      v-model:visible="repairman"
      title="选择修补人员"
      @cancel="handleRepairCancel"
      :draggable="true"
      style="z-index: 1000"
    >
      <a-form :model="ruleForm" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
        <!-- <CorporateSectorCascader
          ref="cascaderRef"
          :configCascader="configCascader"
          @changeCascader="changeCascader"
        /> -->
        <a-form-item field="firm" label="公司">
          <el-input v-model="ruleForm.firm" disabled />
        </a-form-item>
        <a-form-item field="department" label="部门">
          <el-input v-model="ruleForm.department" disabled />
        </a-form-item>
        <a-form-item field="repairUser" label="修补人员">
          <el-select-v2
            v-model="repairUser1"
            :options="repairmanList"
            placeholder="选择修补人员"
            filterable
            remote
            :loading="repairmanLoading"
            clearable
            @click="repairmanFocus"
            :remote-method="repairSearch"
            @change="changeRepairMan"
            @clear="clearRepairMan"
            style="width: 400px"
          />
          <!-- <el-select
            style="width: 400px"
            @focus="repairmanFocus"
            v-model="ruleForm.repairUser"
            filterable
            placeholder="选择员工"
            :loading="repairmanLoading"
          >
            <el-option
              v-for="item in repairmanList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select> -->
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button type="primary" size="small" @click="saveRepairman">保存</a-button>
      </template>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { ref, reactive, onMounted, nextTick, toRaw } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  import printJS from 'print-js'
  import { ElMessage, ElMessageBox } from 'element-plus'
  // 引入
  
  import { localeText } from '@/api/aggridZw'
  import { pagingList } from '@/api/paging'
  import type { FormInstance, FormRules } from 'element-plus'
  import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
  import usePermission from '@/store/modules/permission'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  import filedownload from 'js-file-download'
  interface BrandInfo {
    id: any
    billNumber: string | undefined
    planOrderCode: string | undefined
    greyCode: string | undefined
    greigeName: string | undefined
    machine: string | undefined
    horses: string | undefined
    grade: string | undefined
    processMode: string | undefined
    handler: string | undefined
    disposeTima: string | undefined
    disposeState: string | undefined
    auditPerson: string | undefined
    auditDate: string | undefined
  }

  export default {
    name: 'InspectionExceptionQuery',

    setup() {
      const total = ref(0)
      const page = ref(1)
      const size = ref(10)
      function PageSize(val: any) {
        page.value = val
        doRefresh()
      }
      function change1(val: any) {
        size.value = val
        doRefresh()
      }
      const headerShow = ref<boolean>(true)

      function doRefresh() {
        pageData.pageLoading = true
        updateGridState01()
        post({
          url: 'qms/perchingAnomaly/getInfo',
          data: {
            page: page.value,
            size: size.value,
            deleteState: 0,
            firmId: pageData.company_id,
            planOrderCode: pageData.planOrderCode,
            greigeCode: pageData.greigeCode,
            greigeName: pageData.greigeName,
            resultCode: pageData.resultCode,
            updateName: pageData.updateName,
            // disposeDate: pageData.disposeDate,
            startDate: pageData.disposeDate ? pageData.disposeDate[0] : '',
            endDate: pageData.disposeDate ? pageData.disposeDate[1] : '',
            disposeState: pageData.disposeState,
            checkoutPeople: pageData.checkoutPeople,
            checkoutDate: pageData.checkoutDate,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              // 查询方法改
              gridOption.value.setRowData(data.list)
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }
      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      const tableColumns = useTableColumn([
        {
          title: '公司',
          key: 'outSouringCompany',
          dataIndex: 'outSouringCompany',
          width: 150,
        },
        {
          title: '检验单号',
          key: 'checkoutOdd',
          dataIndex: 'checkoutOdd',
          width: 150,
        },

        {
          title: '织布单号',
          key: 'planOrderCode',
          dataIndex: 'planOrderCode',
          width: 150,
        },
        {
          title: '坯布编号',
          key: 'greigeCode',
          dataIndex: 'greigeCode',
          width: 150,
        },
        {
          title: '坯布名称',
          key: 'greigeName',
          dataIndex: 'greigeName',
          width: 150,
        },
        {
          title: '机台号',
          key: 'machineOdd',
          dataIndex: 'machineOdd',
          width: 150,
        },
        {
          title: '匹号',
          key: 'loneOdd',
          dataIndex: 'loneOdd',
          width: 150,
        },
        {
          title: '等级',
          key: 'perchingGrade',
          dataIndex: 'perchingGrade',
          width: 150,
        },
        {
          title: '问题点',
          key: 'defectNames',
          dataIndex: 'defectNames',
          width: 150,
        },
        {
          title: '处理人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 200,
        },
        {
          title: '处理日期',
          key: 'disposeDate',
          dataIndex: 'disposeDate',
          width: 200,
        },
        {
          title: '二维码',
          key: 'clothfiyCode',
          dataIndex: 'clothfiyCode',
          width: 150,
          slotName: 'clothfiyCode',
        },
        {
          title: '处理方式',
          key: 'resultCode',
          dataIndex: 'resultCode',
          width: 150,
          slotName: 'resultCode',
          fixed: 'right',
        },
        {
          title: '处理状态',
          key: 'disposeState',
          dataIndex: 'disposeState',
          width: 150,
          slotName: 'act',
          fixed: 'right',
        },
        // {
        //     title: "审核人",
        //     key: "checkoutPeople",
        //     dataIndex: "checkoutPeople",
        //     width: 200
        // },
        // {
        //     title: "审核日期",
        //     key: "checkoutDate",
        //     dataIndex: "checkoutDate",
        //     width: 200
        // },
      ])

      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          width: o.width,
          tooltipField: o.key,
        }
        if (o.slotName === 'act') {
          obj['resizable'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 120
          obj['cellRenderer'] = {
            template: `
          <a-space><el-tag type="success" v-if="params.data.disposeState==1">{{val}}</el-tag>
          <el-tag type="warning" v-else>{{val}}</el-tag></a-space>`,
            setup(props: any) {
              let val = ref()
              // if (props.params.data.disposeState == 1) {
              //   val.value = '已处理'
              // } else {
              //   val.value = '未处理'
              // }
              props.params.data.disposeState == 0
                ? (val.value = '未处理')
                : props.params.data.disposeState == 1
                ? (val.value = '已处理')
                : props.params.data.disposeState == 2
                ? (val.value = '修补中')
                : props.params.data.disposeState == 3
                ? (val.value = '已完成')
                : ''
              return {
                val,
              }
            },
          }
          obj['filterParams'] = {
            valueFormatter: function (params: any) {
              return params.value == '0'
                ? '未处理'
                : params.value == '1'
                ? '已处理'
                : params.value == '2'
                ? '修补中'
                : params.value == '3'
                ? '已完成'
                : ''
            },
          }
        }
        if (o.slotName === 'resultCode') {
          obj['resizable'] = false
          obj['sortable'] = false
          obj['width'] = 120
          obj['lockPosition'] = 'right'
          obj['cellRenderer'] = {
            // template: `
            // <a-space>
            //   <el-tag type="warning" v-if="params.data.resultCode==1">{{val}}</el-tag>
            //   <el-tag type="success" v-else-if="params.data.resultCode==0">{{val}}</el-tag>
            //   <el-tag type="info" v-else>{{val}}</el-tag>
            //   </a-space>
            //   `,
            template: `
            <a-select v-model="val" :options="optionsList" v-if="params.data.disposeState==1" @change="resultCodeChange" />
            <a-space v-else>{{val}}</a-space>
            `,
            setup(props: any) {
              let val = ref()
              const optionsList = reactive([
                { label: '本厂修补', value: '本厂修补' },
                { label: '委外修补', value: '委外修补' },
              ])
              if (props.params.data.resultCode == 1) {
                val.value = '委外修补'
              } else if (props.params.data.resultCode == 0) {
                val.value = '本厂修补'
              } else {
                val.value = '入次布仓'
              }
              const resultCodeChange = async (e: any) => {
                try {
                  const res = await post({
                    url: 'qms/perchingAnomaly/update',
                    data: [
                      {
                        id: props.params.data.id,
                        resultCode: e == '本厂修补' ? '0' : e == '委外修补' ? '1' : null,
                      },
                    ],
                  })
                  if (res.code === 200) {
                    Message.success('修改成功')
                    doRefresh()
                  } else {
                    Message.error('修改失败')
                  }
                } catch (e) {
                  console.log(e)
                }
              }
              return {
                val,
                optionsList,
                resultCodeChange,
              }
            },
          }
          obj['filterParams'] = {
            valueFormatter: function (params: any) {
              return params.value == '1' ? '委外修补' : '本厂修补'
            },
          }
        }
        return obj
      })

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      const pageData = reactive<{
        showAdd: boolean
        dropDownData: any
        nameList: []
        pageLoading: boolean
        typeList: []
        dropDownData1: any
        rHeight: any
        btnList: any[]
        isEdit: boolean
        disposeTima: any
        auditDate: any
        planOrderCode: any
        disposeState: any
        printData: any[]
        greigeCode: any
        greigeName: any
        resultCode: any
        updateName: any
        disposeDate: any
        checkoutPeople: any
        checkoutDate: any
        id: any
        company_id: any
        department_id: any
      }>({
        nameList: [],
        showAdd: false,
        dropDownData: '',
        pageLoading: false,
        typeList: [],
        dropDownData1: '',
        rHeight: 0,
        btnList: [],
        isEdit: false,
        disposeTima: '',
        auditDate: '',
        planOrderCode: '',
        disposeState: '',
        printData: [],
        greigeCode: '',
        greigeName: '',
        resultCode: '',
        updateName: '',
        disposeDate: '',
        checkoutPeople: '',
        checkoutDate: '',
        id: '',
        company_id: '',
        department_id: '',
      })

      let selectName: any = ''
      //下拉框得到焦点
      const focusSel = (val: any) => {
        let ob = {}
        ob[val] = ''
        selCxAll(ob)
        selectName = val
      }
      //下拉数据
      const options = ref<any>(pageData.nameList)
      const loading = ref(false)
      const handleSearch = (value: any) => {
        if (value) {
          let ob = {}
          ob[selectName] = value
          loading.value = true
          selCxAll(ob)
          options.value = pageData.nameList
          loading.value = false
        } else {
          options.value = []
        }
      }

      //下拉框查询
      function selCxAll(val: any) {
        post({
          url: 'qms/perchingAnomaly/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.nameList = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      onMounted(() => {
        doRefresh()
      })
      let cxbl = ''
      //查询
      const selectHandler = () => {
        page.value = 1
        doRefresh()
      }

      //创建修补单抽屉
      let drawer = ref<boolean>(false)
      // 表单ref
      const ruleFormRef = ref<FormInstance>()
      //  表单
      // let ruleForm = reactive({
      //   repairUser: '',
      //   repairUserId: '',
      //   startDate: '',
      //   endDate: '',
      //   amount: '',
      //   remark: '',
      //   scannedGreyClothIds: [],
      // })
      //这种写法可以重置表单
      const initialState = () => ({
        repairUser: [],
        repairUser1: '',
        repairUserId: [],
        startDate: '',
        endDate: '',
        amount: '',
        remark: '',
        scannedGreyClothIds: [],
        outSouringCompany: '',
        outSouringCompanyId: null,
        firm: '',
        department: '',
      })
      const ruleForm = reactive(initialState())
      let loadingElplus = ref<boolean>(false)
      // 重置
      let tableData = ref([])
      const dataForm = reactive<BrandInfo>({
        id: null,
        billNumber: '',
        planOrderCode: '',
        greyCode: '',
        greigeName: '',
        machine: '',
        horses: '',
        grade: '',
        processMode: '',
        handler: '',
        disposeTima: '',
        disposeState: '',
        auditPerson: '',
        auditDate: '',
      })
      let repairmanList = ref<any>([])
      // 创建修补单
      let createPatchOrder = () => {
        let selsetionList = gridOption.value.getSelectedRows()
        if (selsetionList.length == 0) {
          Message.warning('请选择您的单据')
          return
        }
        if (new Set(selsetionList.map((res: any) => res.outSouringCompanyId)).size > 1) {
          Message.warning('请勾选相同公司')
          return
        }
        interface lx {
          disposeState: string | number
        }
        let condition = selsetionList.every(
          (item: lx) =>
            item.disposeState == 1 && item.disposeState === selsetionList[0].disposeState
        )
        if (!condition) {
          Message.warning('请选择处理状态为已处理的单据')
          return
        }
        selsetionList.forEach((item: any) => {
          if (item.resultCode == 0) {
            item.resultCode = '本厂修补'
          } else if (item.resultCode == 1) {
            item.resultCode = '委外修补'
          }
        })
        Object.assign(ruleForm, initialState())
        //转换后台需要的id数组
        let ClothIds = selsetionList.reduce((pre: any, cur: any) => {
          return pre.concat(Number(cur.scannedGreyClothId))
        }, [])
        ruleForm.scannedGreyClothIds = ClothIds
        ruleForm.outSouringCompany = selsetionList[0].outSouringCompany
        ruleForm.outSouringCompanyId = selsetionList[0].outSouringCompanyId
        // 选中的值给表格
        tableData.value = selsetionList
        // 打开前重置form表单
        drawer.value = true
      }
      let rTime = (date: string) => {
        var json_date = new Date(date).toJSON()
        return new Date(new Date(json_date) + 8 * 3600 * 1000)
          .toISOString()
          .replace(/T/g, ' ')
          .replace(/\.[\d]{3}Z/, '')
      }
      //保存修补单
      let save = async () => {
        if (!ruleForm.startDate) {
          Message.warning('开始时间必填!')
          return
        }
        if (!ruleForm.endDate) {
          Message.warning('结束时间必填!')
          return
        }
        if (new Date(ruleForm.startDate) > new Date(ruleForm.endDate)) {
          Message.warning('开始时间请勿大于结束时间!')
          return
        }
        if (ruleForm.endDate) {
          ruleForm.endDate = rTime(ruleForm.endDate)
        }
        if (ruleForm.startDate) {
          ruleForm.startDate = rTime(ruleForm.startDate)
        }
        const params = JSON.parse(JSON.stringify(ruleForm))
        params.repairUser = params.repairUser.join(',')
        params.repairUserId = params.repairUserId.join(',')
        delete params.firm
        delete params.repairUser1
        try {
          loadingElplus.value = true
          let res: any = await post({ url: 'qms/repairOrder/createRepairOrder', data: params })
          if (res.code == 200) {
            ElMessage({
              type: 'success',
              message: '创建成功',
            })
            doRefresh()
            drawer.value = false
            loadingElplus.value = false
            return
          }
          Message.error(res.message)
        } finally {
          loadingElplus.value = false
        }
      }
      const repairman = ref<boolean>(false)
      let cascaderRef = ref('')
      let configCascader = ref<{}>({
        cascaderShow: 'sector',
        corporateNameLabelWidth: '60px',
        corporateWidth: '230px', //公司宽度
        corporateRquired: false, //公司是否必填
        size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
        corporateName: '公司', //公司label
      })
      // 需要传递后端的数据
      const CascaderData = reactive({
        company_id: '',
        obsoleteState: 0,
        deleteState: 0,
        page: 1,
        size: 30,
        ygText: '',
      })
      //公司组件选择触发事件
      const changeCascader = (data: any) => {
        const { corporateId, sectorId } = data
        pageData.id = ''
        repairmanList.value = []
        pageData.company_id = corporateId
        pageData.department_id = sectorId
      }
      //输入时去掉id
      let repaInput = () => {
        if (ruleForm.repairUserId) {
          ruleForm.repairUserId = ''
        }
      }
      const repairmanObj = {}
      //保存修补员按钮
      const saveRepairman = () => {
        let label = repairmanList.value.filter((item: any) => {
          return item.id == repairUser1.value
        })
        if (ruleForm.repairUser.indexOf(label[0].name) == -1) {
          ruleForm.repairUser.push(label[0].name)
          ruleForm.repairUserId.push(label[0].id.toString())
          repairmanObj[label[0].name] = label[0].id
        }
        repairman.value = false
        ruleForm.firm = ''
        ruleForm.department = ''
      }
      //打开员工弹窗
      const clickRepairman = () => {
        CascaderData.company_id = ruleForm.outSouringCompanyId
        repairman.value = true
        nextTick(() => {
          repairUser1.value = ''
          repairmanList.value = []
          // cascaderRef.value.resetForm()
        })
      }
      let repairUser1 = ref('')
      let repairmanLoading = ref<boolean>(false)
      //查询员工接口
      const repairmanFocus = async (e, text: string = '') => {
        try {
          repairmanLoading.value = true
          CascaderData.ygText = text
          let res: any = await post({ url: 'org/hrEmployee/getPage', data: CascaderData })
          if (res.code == 200) {
            res.data.list.map((item: any) => {
              item.value = item.id
              item.label = item.code + '/' + item.name
            })
            repairmanList.value = res.data.list
            repairmanLoading.value = false
            return
          }
          Message.error(res.message)
        } finally {
          repairmanLoading.value = false
        }
      }
      // 表格准备事件
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }
      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        //  flex: 1
      }
      //打印弹窗
      const visible = ref(false)
      const handleClick = () => {
        pageData.printData = gridOption.value.getSelectedRows()
        if (pageData.printData.length == 0) {
          Message.error({
            content: '请先勾选数据',
            duration: 5000,
          })
          return
        }
        visible.value = true
      }
      const handleOk = () => {
        visible.value = false
        printJS({
          printable: 'inspect',
          type: 'html',
          targetStyles: ['*'],
        })
      }
      const handleCancel = () => {
        visible.value = false
      }
      //是否审核
      const auditHandler = () => {
        let list = gridOption.value.getSelectedRows()
        if (list.length == 0) {
          Message.error({
            content: '请先勾选数据',
            duration: 5000,
          })
          return
        }
        let ob = {}
        ob['disposeState'] = 1
        ob['id'] = list
        list.forEach(function (o: any) {
          o['disposeState'] = 1
        })
        Modal.confirm({
          title: '系统提示',
          content: '是否审核此数据',
          onOk() {
            post({
              url: 'qms/perchingAnomaly/setAudit',
              data: ob,
            }).then(({ data, code, message }: any) => {
              if (code === 200) {
                pageData.nameList = data
              } else {
                Message.error({
                  content: message,
                  duration: 5000,
                })
              }
            })
          },
        })
      }
      const localeText1: any = ref(localeText)
      const huiche = () => {
        doRefresh()
      }
      const pagingList1: any = ref(pagingList)
      const permissionStore = usePermission()
      if (permissionStore.hasPermisson('jyyccx.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('jyyccx.xz')) {
        pageData.btnList.push('创建修补单')
      }
      if (permissionStore.hasPermisson('jyyccx.dc')) {
        pageData.btnList.push('全部导出')
      }
      // if (permissionStore.hasPermisson('jyyccx.dc')) {
      //   pageData.btnList.push('打印')
      // }
      if (permissionStore.hasPermisson('jyyccx.xg')) {
        pageData.isEdit = true
      }

      const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
        saveOrUpdateGridState01('InspectionExceptionQuery', gridOption, colState, tc)
      const onColumnMoved = () => {
        saveGridState01()
      }
      const onColumnResized = () => {
        saveGridState01()
      }
      const onColumnVisible = () => {
        saveGridState01()
      }
      const exportAll = () => {
        post({
          url: 'qms/perchingAnomaly/excelAllPerchingAnomaly',
          data: {
            deleteState: 0,
            planOrderCode: pageData.planOrderCode,
            greigeCode: pageData.greigeCode,
            greigeName: pageData.greigeName,
            resultCode: pageData.resultCode,
            updateName: pageData.updateName,
            disposeDate: pageData.disposeDate,
            disposeState: pageData.disposeState,
            checkoutPeople: pageData.checkoutPeople,
            checkoutDate: pageData.checkoutDate,
          },
          responseType: 'blob',
        }).then((res: any) => {
          filedownload(res, '检验修补异常报告.xlsx')
        })
      }
      const repairSearch = (val: string) => {
        repairmanFocus('e', val)
      }
      const changeRepairMan = (id: string) => {
        const personData = repairmanList.value.find((item: any) => item.id == id)
        if (personData) {
          ruleForm.firm = personData.companyName
          ruleForm.department = personData.departmentName
        }
      }
      const clearRepairMan = () => {
        ruleForm.firm = ''
        ruleForm.department = ''
      }
      const handleRepairCancel = () => {
        repairman.value = false
        ruleForm.firm = ''
        ruleForm.department = ''
      }
      const handleRemoveTag = (removed: any) => {
        ruleForm.repairUserId = ruleForm.repairUserId.filter(
          (item: any) => item != repairmanObj[removed]
        )
      }
      return {
        handleRemoveTag,
        handleRepairCancel,
        clearRepairMan,
        changeRepairMan,
        repairSearch,
        saveOrUpdateGridState01,
        saveGridState01,
        updateGridState01,
        onColumnMoved,
        onColumnResized,
        onColumnVisible,
        colState,
        pagingList1,
        huiche,
        localeText1,
        auditHandler,
        handleCancel,
        handleOk,
        handleClick,
        visible,
        defaultColDef,
        tc,
        total,
        PageSize,
        change1,
        page,
        size,
        dataForm,
        selectedRowKeys,
        createPatchOrder,
        drawer,
        pagination,
        tableColumns,
        ruleFormRef,
        ruleForm,
        table,
        rowKey,
        pageData,
        selectHandler,
        options,
        loading,
        handleSearch,
        focusSel,
        headerShow,
        handleChange,
        gridReady,
        printJS,
        tableData,
        save,
        loadingElplus,
        configCascader,
        changeCascader,
        repairman,
        cascaderRef,
        repairmanList,
        repairmanFocus,
        clickRepairman,
        repairmanLoading,
        saveRepairman,
        repaInput,
        repairUser1,
        rTime,
        permissionStore,
        exportAll,
      }
    },
    components: { Toolbar, PageTabelLayout, CorporateSectorCascader },
  }
</script>
<style scoped>
  #Table td,
  #Table th {
    border: 1px solid #ccc;
    padding: 10px;
  }

  #Table {
    border-collapse: collapse;
  }

  .tdStyle {
    min-width: 100px;
  }
</style>
<style>
  .repairman-options {
    display: none !important;
  }
</style>
